package com.apes.scm.masterdata.car.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.car.repository.CarModelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @Auther: linwz
 * @Date: 2018/7/19 18:32
 */
@Service("carModelService")
public class CarModelService extends DomainService {

    @Autowired
    CarModelRepository carModelRepository;

    public CarModel save(SimpleRequest request) {
        CarModel carModel = request.getO(CarModel.class);
        return carModelRepository.saveAndFlush(carModel);
    }

    public String delete(SimpleRequest request) {
        String id = request.get("id");
        Integer versions = request.get("version");
        CarModel carModel = request.getO(CarModel.class);
        if (carModel == null) throw new RuntimeException("车型【"+ id +"】在系统中不存在。");
        if (carModel.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        carModelRepository.delete(carModel);
        return "删除成功";
    }


    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<CarModel> findAll(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return carModelRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 功能：查询
     *
     * @param request
     */
    public Page<CarModel> find(SimpleRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return carModelRepository.findAll(PageRequest.of(request.get("page"), request.get("size"), sort));
    }

}
